/**
 * JWT中间件
 */

const { secret, tokenExpired } = require('../config.json');
const { sign } = require('jsonwebtoken');

module.exports = async (ctx, next) => {
    try {
        await next();
    } catch (error) {
        throw error;
    } finally {
        if (ctx.state.user) {
            const { id, username } = ctx.state.user;
            ctx.set('newtoken', sign({ id, username }, secret, { expiresIn: tokenExpired }));
            ctx.set('Access-Control-Expose-Headers', 'newtoken');
        }
    }
}